package com.qf.controller;

import com.alibaba.fastjson.JSON;
import com.qf.pojo.User;
import com.qf.service.UserService;
import com.qf.utils.SYS;
import com.qf.vo.MsgResult;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Locale;

@Controller
@RequestMapping("/user")
public class UserController {

    @Resource
    private UserService userService;

    @RequestMapping(value = "/tologIn",method = RequestMethod.POST)
    public ModelAndView logIn(String username, String password, String unicode, String rememberme, HttpSession session,HttpServletResponse resp){
        User user=userService.logIn(username,password);
        unicode=unicode.toUpperCase();
        System.out.println("登录：用户名="+username+"；密码="+password);
        ModelAndView mav=new ModelAndView();
        if (user != null) {
            //获得会话中的验证码
            Object obj = session.getAttribute(SYS.CODE);
            if (obj != null && obj instanceof String) {
                String code=(String)obj;
                System.out.println("获得会话中的验证码="+code);
                //验证码正确
                System.out.println("用户输入的验证码="+code);
                if (unicode.equals(code)) {
                    mav.addObject(SYS.USER,user);
                    session.setAttribute(SYS.USER, user);
                    //点击了记住密码
                    if (rememberme!=null&&rememberme.equals("yes")) {
                        String name = null;
                        try {
                            name = URLEncoder.encode(username, "UTF-8");
                        } catch (UnsupportedEncodingException e) {
                            e.printStackTrace();
                        }
                        Cookie cookie = new Cookie(name, password);
                        cookie.setMaxAge(7 * 24 * 60 * 60);//有效期7*24小时,7天,单位秒
                        resp.addCookie(cookie);
                        mav.setViewName("redirect:/load");
                        return mav;
                    }
                    //成功转到首页
                    mav.setViewName("redirect:/load");
                    return mav;
                }else{
                    //验证码不对
                    mav.addObject("username", username);
                    mav.addObject("error", "验证码填写错误，请刷新验证码！");
                    mav.setViewName("/logIn");
                    return mav;
                }
            }else {
                //验证码后台获取失败
                mav.addObject("username", username);
                mav.addObject("error", "数据异常，重新登录！");
                mav.setViewName("/logIn");
                return mav;
            }
        } else {
            //数据库没有查到，登录失败；
            //携带错误信息返回
            mav.addObject("username", username);
            mav.addObject("error", "用户名或密码填写有误！登录失败！");
            mav.setViewName("/logIn");
            return mav;
        }
    }

    //用户注销
    @RequestMapping(value = "/logOut",method = RequestMethod.GET)
    public String logOut(HttpSession session){
        session.invalidate();
        return "redirect:/load";
    }

    @RequestMapping(value = "/regist",method = RequestMethod.POST)
    protected ModelAndView regist(User user) throws ServletException, IOException {
        ModelAndView mav=new ModelAndView();
        System.out.println("注册用户："+user);
        int res = userService.regist(user);
        MsgResult msg = new MsgResult();
        if (res == 1) {
            msg.setCode(200);
            msg.setMsg(user.getName() + "注册成功!");
            mav.addObject("msgresult", msg);
        } else {
            msg.setCode(100);
            msg.setMsg(user.getName() + "注册失败！请返回！");
            mav.addObject("msgresult", msg);
        }
        mav.setViewName("res");
        return mav;
    }

    //输入用户名时是自动填充密码
    //免登录
    @ResponseBody
    @RequestMapping(value = "/autoInsert",method = RequestMethod.POST)
    protected String autoInsretPass(String userName,HttpServletRequest req) {
        System.out.println("dogetpass...for:" + userName);
        String name = null;
        try {
            name = URLEncoder.encode(userName, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        Cookie[] cookies = req.getCookies();
        for (Cookie ck : cookies) {
            // String cookname = URLDecoder.decode(ck.getValue(),"UTF-8");
            if (ck.getName().equals(name)) {
                return ck.getValue();
            }
        }
        return null;
    }

    //checkUserName
    //注册是自动查找用户名是否可用
    @ResponseBody
    @RequestMapping(value = "/checkUserName",method = RequestMethod.POST)
    public MsgResult checkNameAvailable(String userName) {
        MsgResult msg = new MsgResult();
        if (userName != null) {
            User user = userService.getPass(userName);
            if (user == null) {
                msg.setCode(1);
                msg.setMsg(userName + "是一个可用的用户名!");
                return msg;
            } else {
                msg.setCode(0);
                msg.setMsg(userName + "，当前用户名重复，请更换！");
                return msg;
            }
        }
        return null;
    }
}
